#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author  : config_spider
import json

import scrapy
import math

from apps.tax_policy.tax_policy.items import NetTaxPolicyItem as Item, urlencode, urllib
from apps.tax_policy.tax_policy.spiders.base_spider.base_tax_policy_spider import BaseTaxPolicySpider


class GansuQingyangPolicy(BaseTaxPolicySpider):
    name = 'gansu_qingyang_qu2_policy'
    
    province = '甘肃省'
    city: str = "庆阳市"  # 取表格
    # county: str = ""  # 取表格
    park: str = ""  # 取表格

    @classmethod
    def update_settings(cls, settings) -> None:
        downloader_middlewares = settings.getdict("DOWNLOADER_MIDDLEWARES")
        new_settings = {
            **(cls.custom_settings or {}),
            **{
                "DOWNLOADER_MIDDLEWARES": {
                    # "scrapy.downloadermiddlewares.useragent.UserAgentMiddleware": None,  # 为 None 失效
                    "scrapy.downloadermiddlewares.retry.RetryMiddleware": None,  # 为 None 失效
                    "components.middlewares.downloadmiddlewares.public.useragent_random.RandomUserAgentMiddleware": 550,
                    "components.middlewares.downloadmiddlewares.public.company_ip_by_api.CompanyIpByApiMiddleware": 551,
                    "components.middlewares.downloadmiddlewares.public.error_collector.ErrorCollectorMiddleware": 552,
                    'components.middlewares.downloadmiddlewares.private.rs_6_middlewares.Rs6RetryMiddleware': 553,
                },
                "DOWNLOAD_TIMEOUT": 200,
                # 'CONCURRENT_REQUESTS': 1,
                # "HTTPERROR_ALLOWED_CODES": [400, 404, 500, 200, 202, 502, 412],
            },
        }
        settings.setdict(new_settings or {}, priority="spider")

    def start_requests(self):
        for source, county, url in [
            # ['庆城县人民政府', '庆城县', 'https://www.chinaqingcheng.gov.cn/zwgk/zc/hzgfxwj'],
            ['庆城县人民政府', '庆城县', 'https://www.zgqingyang.gov.cn/gk/zfxxgk/zc/dfxfg'],
            # ['庆城县人民政府', '庆城县', 'https://www.chinaqingcheng.gov.cn/zwgk/zfwj'],
            ['庆城县工信局', '庆城县', 'https://www.chinaqingcheng.gov.cn/zwgk/zfbmxxgk/zfgzbm/33gxj/bmwj1633gxj'],
            ['庆城县财政局', '庆城县', 'https://www.chinaqingcheng.gov.cn/zwgk/zfbmxxgk/zfgzbm/18czj/bmwj218czj'],
            ['庆城县人社局', '庆城县', 'https://www.chinaqingcheng.gov.cn/zwgk/zfbmxxgk/zfgzbm/38rsj/bmwj2138rsj'],
            ['环县人民政府', '环县', 'https://www.huanxian.gov.cn/zwgk/zc/gfxwj'],
            ['环县人民政府', '环县', 'https://www.huanxian.gov.cn/zwgk/zcgk/hzf'],
            ['环县人民政府', '环县', 'https://www.huanxian.gov.cn/zwgk/zcgk/hzbf'],
            ['环县发改局', '环县', 'https://www.huanxian.gov.cn/fgj/wj'],
            ['环县科技局', '环县', 'https://www.huanxian.gov.cn/kjj/wj'],
            ['环县工信局', '环县', 'https://www.huanxian.gov.cn/gxj/wj'],
            ['环县财政局', '环县', 'https://www.huanxian.gov.cn/czj/wj'],
            ['环县商务局', '环县', 'https://www.huanxian.gov.cn/sw/wj'],
        ]:
            item = {'source': source, 'county': county}
            yield scrapy.Request(url, callback=self.parse_list, meta={"item": item})

    def parse_list(self, response, **kwargs):
        meta = response.meta
        prev_item = meta.get('item')
        # print(params)
        elem_list = response.xpath("//ul[@class='infoList']//li")

        for elem in elem_list:
            item = Item()
            item['source_url'] = elem.xpath(""".//a[@title]/@href""").get()
            # item['title'] = elem.xpath(""".//a[@title]/@title""").get() or elem.xpath(""".//a/text()""").get()
            item['source_url'] = response.urljoin(item['source_url'])
            item['publish_date'] = elem.xpath("./span/text()").re_first(r"\d{4}-\d{2}-\d{2}")
            if prev_item is not None:
                for key, value in prev_item.items():
                    item[key] = value
            if not item['source_url']:
                continue
            if '#relativeInfo' in item['source_url']:
                continue
            # print(params, item['source_url'])
            yield response.follow(item['source_url'], callback=self.parse_detail, meta={'item': item})
        next_url = response.xpath("//*[contains(text(), '下一页')]/@href").get()
        # total_page = response.xpath("//span[@class='p_no']/a/text()").getall()[-1]
        print(response.url, len(elem_list), 'next_url', next_url)
        if next_url and 'javascript:void(0)' not in next_url:
            meta.update({'item': prev_item})
            yield response.follow(next_url, callback=self.parse_list, meta=meta)

    def parse_detail(self, response, **kwargs):
        item = Item() if response.meta.get('item') is None else response.meta.get('item')
        item['title'] = response.xpath("""string(//meta[@name='ArticleTitle']/@content)""").get()
        # item['publish_date'] = response.xpath("""string(//meta[@name='PubDate']/@content)""").get()
        item['content'] = response.xpath(""".""").get()
        item['province'] = self.province
        item['city'] = self.city
        item['park'] = self.park
        # item['source'] = self.source
        yield item


if __name__ == "__main__":
    from scrapy import cmdline

    cmdline.execute("scrapy crawl gansu_qingyang_qu2_policy".split())
